// pages/Itinerary/searchList/searchList.js
import { getItineraryListForPage } from '../../api/home'
import { imageURL } from '../../../utils/request'

Page({
  data: {
    imageURL:'',
    itineraryList: [],
    page: 1,
    rows: 10,
    hasMore: true,
    loading: false,
    keyword: '' // 搜索关键字
  },

  onLoad() {
    this.setData({imageURL})
    this.loadItineraryList()
  },
  goItineraryDetails(e){
    const itinerary_id = e.currentTarget.dataset.itinerary_id
    wx.navigateTo({
      url: `/pages/Itinerary/ItineraryDetails/ItineraryDetails?itinerary_id=${itinerary_id}`,
    })
  },
  // 输入框事件
  onInput(e) {
    this.setData({
      keyword: e.detail.value
    })
  },

  // 点击键盘搜索
  onSearch() {
    // 重置列表
    this.setData({
      itineraryList: [],
      page: 1,
      hasMore: true
    })
    this.loadItineraryList()
  },

  // 加载行程列表
  async loadItineraryList() {
    if (!this.data.hasMore || this.data.loading) return

    this.setData({ loading: true })

    try {
      const res = await getItineraryListForPage({
        page: this.data.page,
        rows: this.data.rows,
        // is_recommend: 0,
        keyword: this.data.keyword   // 传入搜索关键词
      })

      const newList = Array.isArray(res.data.list) ? res.data.list : []

      // 拼接完整图片路径
      newList.forEach(item => {
        if (item.image && !item.image.startsWith('http')) {
          item.image = imageURL + item.image
        }
      })

      this.setData({
        itineraryList: [...this.data.itineraryList, ...newList],
        page: this.data.page + 1,
        hasMore: newList.length === this.data.rows,
        loading: false
      })
    } catch (err) {
      console.error('获取搜索结果失败:', err)
      this.setData({ loading: false })
    }
  },

  // 触底事件
  onReachBottom() {
    this.loadItineraryList()
  }
})
